package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostsService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {
    @Autowired
    public DiscussPostsService discussPostsService;

    @Autowired
    public UserService userService;

    @Autowired
    private LikeService likeService;

    // 进入到首页，按顺序显示帖子，页面有帖子数量限制，并做好分页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page, @RequestParam(name = "orderMode", defaultValue = "0") int orderMode) {
        // 方法调用前 springmvc会自动实例化model和page，并将page注入给model
        // 所以在thymeleaf模板中可以直接访问page对象中的数据
        page.setRows(discussPostsService.findDiscussPostRows(0));
        page.setPath("index?orderMode=" + orderMode);

        List<DiscussPost> list = discussPostsService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        // 打断点以debug模式运行，F8表示向下执行一行，F7表示进入到方法内部,F9跳到下一个断点
        List<Map<String, Object>> discussPosts = new ArrayList<>();

        if(list != null){
            for(DiscussPost discussPost : list){
                Map<String, Object> map = new HashMap<>();
                map.put("post", discussPost);
                User user = userService.findUserById(discussPost.getUserId());
                map.put("user", user);
                discussPosts.add(map);

                // 赞
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPost.getId());
                map.put("likeCount", likeCount);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("orderMode", orderMode);
        return "index";
    }

    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String getErrorPage(){
        return "error/500";
    }

    // 没有权限跳转路径
    @RequestMapping(value = "/denied", method = RequestMethod.GET)
    public String getDeniedPage(){
        return "error/404";
    }


}


























